package com.yuntoyun.fwcore.base;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */
import android.graphics.Color;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.yuntoyun.fwcore.R;
import com.yuntoyun.fwcore.adapter.FwBaseRecyclerViewAdapter;
import com.yuntoyun.fwcore.base.ext.RecyclerViewOnScrollListener;
import com.yuntoyun.fwcore.base.ext.RvGridLayoutManager;
import com.yuntoyun.fwcore.base.ext.RvLinearLayoutManager;
import com.yuntoyun.fwcore.base.ext.RvStaggeredGridLayoutManager;
import com.yuntoyun.fwcore.config.FwAppConfig;
import com.yuntoyun.fwcore.config.FwCodeConfig;
import com.yuntoyun.fwcore.model.FwRecyclerViewAdapterModel;
import com.yuntoyun.fwcore.model.FwRecyclerViewPostModel;
import com.yuntoyun.fwcore.model.FwResultJsonListDataModel;
import com.yuntoyun.fwcore.plug.network.retrofit.FwOkHttp;
import com.yuntoyun.fwcore.util.FwGsonUtil;
import com.yuntoyun.fwcore.util.FwToastUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

/**
 * 应用 RecyclerView 组件 Fragment 基础类
 */
public abstract class FwBaseRecyclerViewFragment extends FwBaseFragment implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    SwipeRefreshLayout srl_swipeRefreshLayout;
    RecyclerView rvw_recyclerView;
    ImageView ivw_scroll_top;

    //+++++++++++++++++++++++
    //核心参数
    //+++++++++++++++++++++++
    //RecyclerView数据适配器
    protected BaseQuickAdapter fwRecyclerViewAdapter;
    //RecyclerView数据源
    protected List<JsonObject> fwRecyclerViewDataList = new ArrayList<JsonObject>();
    //当前页
    protected int fwCurrentPage = 1;
    // 总页数
    private int fwTotalPages = 1;
    //加载类型：0 刷新数据，1 加载更多数据
    private int isRefreshOrLoadmore = 0;

    @Override
    protected void initView(View layoutView) {
        //初始化控制
        srl_swipeRefreshLayout = layoutView.findViewById(R.id.srl_swipeRefreshLayout);
        rvw_recyclerView = layoutView.findViewById(R.id.rvw_recyclerView);
        ivw_scroll_top = layoutView.findViewById(R.id.ivw_scroll_top);

        srl_swipeRefreshLayout.setOnRefreshListener(this);
        srl_swipeRefreshLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        srl_swipeRefreshLayout.setRefreshing(true);

        rvw_recyclerView.setLayoutManager(getLayoutManager());
        fwRecyclerViewAdapter = getAdapter();
        rvw_recyclerView.setAdapter(fwRecyclerViewAdapter);

        this.initChildView();
        this.loadView();
    }

    @Override
    protected void initData() {
        this.onRefresh();
        this.initChildData();
    }

    @Override
    protected void initEvent() {
        //监听RecyclerView滚动事件
        rvw_recyclerView.addOnScrollListener(recyclerOnScrollListener);
        fwRecyclerViewAdapter.setOnItemClickListener(this);
        fwRecyclerViewAdapter.setOnItemChildClickListener(this);
        ivw_scroll_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rvw_recyclerView.scrollToPosition(0);
                ivw_scroll_top.setVisibility(View.GONE);
            }
        });
        this.initChildEvent();
    }

    @Override
    protected void messageHandler(FwResultJsonListDataModel model) {
        switch (model.getIndex()) {
            case FwCodeConfig.MESSAGE_WHAT_RECYCLERVIEW:
                resultHandler(model);
                break;
            default:
                childMessageHandler(model);
                break;
        }
    }

    /**
     * RecyclerView 滚动事件
     */
    protected RecyclerViewOnScrollListener recyclerOnScrollListener = new
            RecyclerViewOnScrollListener() {

                @Override
                public void onScrolled(int dx, int dy) {
                    super.onScrolled(dx, dy);
                    if (dy == 0 || dy < 50) {
                        ivw_scroll_top.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onScrollUp() {
                    // 滑动时隐藏float button
                    if (ivw_scroll_top.getVisibility() == View.VISIBLE) {
                        ivw_scroll_top.setVisibility(View.GONE);
                        animate(ivw_scroll_top, R.anim.fw_floating_button_hide);
                    }
                }

                @Override
                public void onScrollDown() {
                    if (ivw_scroll_top.getVisibility() != View.VISIBLE) {
                        ivw_scroll_top.setVisibility(View.VISIBLE);
                        animate(ivw_scroll_top, R.anim.fw_floating_button_show);
                    }
                }

            };

    /**
     * 获取自定义流布局管理器
     *
     * @param lme       LinearLayout以此开头的枚举值设置spanCount为0即可，其他值必须设置spanCount大于0
     * @param spanCount 仅作用于非LinearLayout开头的枚举值
     * @return
     */
    protected RecyclerView.LayoutManager getCustomLayoutManager(LayoutManangerEnum lme, int
            spanCount) {

        RecyclerView.LayoutManager layoutManager = null;

        switch (lme) {
            case LinearLayoutVertical:
                layoutManager = new RvLinearLayoutManager(fwActivity);
                break;
            case LinearLayoutHorizontal:
                layoutManager = new RvLinearLayoutManager(fwActivity,
                        RvLinearLayoutManager.HORIZONTAL,
                        false);
                break;
            case LinearLayoutVerticalReversel:
                layoutManager = new RvLinearLayoutManager(fwActivity,
                        RvLinearLayoutManager.VERTICAL,
                        true);
                break;
            case LinearLayoutHorizontalReversel:
                layoutManager = new RvLinearLayoutManager(fwActivity,
                        RvLinearLayoutManager.HORIZONTAL,
                        true);
                break;
            case StaggeredGridHorizontal:
                layoutManager = new RvStaggeredGridLayoutManager(spanCount,
                        RvStaggeredGridLayoutManager.HORIZONTAL);
                break;
            case StaggeredGridVertical:
                layoutManager = new RvStaggeredGridLayoutManager(spanCount,
                        RvStaggeredGridLayoutManager.VERTICAL);
                break;
            case LinearGridVertical:
                layoutManager = new RvGridLayoutManager(fwActivity, spanCount);
                break;
            case LinearGridVerticalReverse:
                layoutManager = new RvGridLayoutManager(fwActivity, spanCount, RvLinearLayoutManager
                        .VERTICAL, true);
                break;
            case LinearGridHorizontal:
                layoutManager = new RvGridLayoutManager(fwActivity, spanCount, RvLinearLayoutManager
                        .HORIZONTAL, false);
                break;
            case LinearGridHorizontalReverse:
                layoutManager = new RvGridLayoutManager(fwActivity, spanCount, RvLinearLayoutManager
                        .HORIZONTAL, true);
                break;
        }

        return layoutManager;
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        JsonObject itemData = fwRecyclerViewDataList.get(position);
        this.onItemChildClickHandler(itemData, view, position);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        JsonObject itemData = fwRecyclerViewDataList.get(position);
        this.onItemClickHandler(itemData, view, position);
    }

    /**
     * 布局管理器枚举
     */
    protected enum LayoutManangerEnum {
        LinearLayoutVertical, LinearLayoutHorizontal,
        LinearLayoutVerticalReversel, LinearLayoutHorizontalReversel,
        StaggeredGridHorizontal, StaggeredGridVertical,
        LinearGridVertical, LinearGridVerticalReverse, LinearGridHorizontal,
        LinearGridHorizontalReverse
    }

    protected abstract void initChildView();

    protected abstract void initChildData();

    protected abstract void initChildEvent();

    protected abstract FwRecyclerViewPostModel getRequestModel();

    protected abstract FwRecyclerViewAdapterModel getAdapterModel();

    protected abstract RecyclerView.LayoutManager getLayoutManager();

    protected abstract void setResultData(JsonObject data);

    protected abstract void onItemClickHandler(JsonObject data, View view, int position);

    protected abstract void onItemChildClickHandler(JsonObject data, View view, int position);

    protected abstract void childMessageHandler(FwResultJsonListDataModel model);

    protected abstract View getHeaderView();

    protected abstract View getFooterView();

    @Override
    public void onRefresh() {
        fwRecyclerViewAdapter.setEnableLoadMore(false);
        rvw_recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                fwCurrentPage = 1;
                int size = fwRecyclerViewDataList.size();
                fwRecyclerViewDataList.clear();
                fwRecyclerViewAdapter.notifyItemRangeRemoved(fwRecyclerViewAdapter
                        .getHeaderLayoutCount(), size);
                isRefreshOrLoadmore = 0;
                loadData();
            }
        }, FwAppConfig.RECYCLERVIEW_DO_TIMEOUT);
    }

    @Override
    public void onLoadMoreRequested() {
        srl_swipeRefreshLayout.setEnabled(false);
        rvw_recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {
                isRefreshOrLoadmore = 1;
//                if (fwCurrentPage >= fwTotalPages) {
//                    fwRecyclerViewAdapter.loadMoreEnd(false);
//                } else {
//                    loadData();
//                }
                loadData();
                srl_swipeRefreshLayout.setEnabled(true);
            }
        }, FwAppConfig.RECYCLERVIEW_DO_TIMEOUT);
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    private void loadData() {
        FwRecyclerViewPostModel model = getRequestModel();
        super.doPostListData(FwCodeConfig.MESSAGE_WHAT_RECYCLERVIEW, model.getObservable(),
                model.isShowLoading());
    }

    private BaseQuickAdapter getAdapter() {
        FwRecyclerViewAdapterModel model = getAdapterModel();
        fwRecyclerViewAdapter = new FwBaseRecyclerViewAdapter(fwActivity, model.getItemResId(),
                fwRecyclerViewDataList, model.getViewHolder());
        if (model.getEmptyResId() > 0) {
            View view = super.fwLayoutInflater.inflate(model.getEmptyResId(),
                    null, false);
            fwRecyclerViewAdapter.setEmptyView(view);
        } else if (null != model.getEmptyView()) {
            fwRecyclerViewAdapter.setEmptyView(model.getEmptyView());
        } else {
            View view = super.fwLayoutInflater.inflate(R.layout.fw_layout_list_nodata,
                    null, false);
            fwRecyclerViewAdapter.setEmptyView(view);
        }
        fwRecyclerViewAdapter.setOnLoadMoreListener(this, rvw_recyclerView);
        fwRecyclerViewAdapter.openLoadAnimation();
        return fwRecyclerViewAdapter;
    }

    private void resultHandler(FwResultJsonListDataModel fwResultJsonListDataModel) {
        srl_swipeRefreshLayout.setRefreshing(false);
        fwRecyclerViewAdapter.setEnableLoadMore(true);
        //加载List中的Data数据
        this.setResultData(fwResultJsonListDataModel.getFwData());
        //处理结果核心代码
        int status = fwResultJsonListDataModel.getFwStatus();
        if (FwCodeConfig.CODE_SUCCESSED == status) {
            fwTotalPages = fwResultJsonListDataModel.getFwTotalPage();
            JsonArray list = fwResultJsonListDataModel.getFwList();
            if (list.size() != 0) {
                fwCurrentPage = fwCurrentPage + 1;
                this.resultListHandler(list);
                if (isRefreshOrLoadmore == 0) {
                    fwRecyclerViewAdapter.setNewData(fwRecyclerViewDataList);
                } else {
                    fwRecyclerViewAdapter.loadMoreComplete();
                }
            } else {
                fwRecyclerViewAdapter.loadMoreEnd(false);
            }
        } else {
            fwRecyclerViewAdapter.loadMoreFail();
            FwToastUtil.builder().makeText(fwResultJsonListDataModel.getFwMessage());
        }
    }

    private void resultListHandler(JsonArray list) {
        for (int i = 0; i < list.size(); i++) {
            JsonObject item = (JsonObject) FwGsonUtil.builder().getJsonObject(list, i);
            fwRecyclerViewDataList.add(item);
        }
    }

    /**
     * 设置动画
     *
     * @param view
     * @param anim
     */
    private void animate(View view, int anim) {
        if (anim != 0) {
            Animation a = AnimationUtils.loadAnimation(view.getContext(), anim);
            view.startAnimation(a);
        }
    }

    private void loadView() {
        View headerView = getHeaderView();
        if (null != headerView) {
            fwRecyclerViewAdapter.addHeaderView(headerView);
        }
        View footerView = getFooterView();
        if (null != footerView) {
            fwRecyclerViewAdapter.addFooterView(footerView);
        }
    }
}
